package com.example.myapplication.ui

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Handler
import android.util.Log
import android.view.ContextMenu
import android.view.ContextMenu.ContextMenuInfo
import android.view.MenuItem
import android.view.View
import android.widget.*
import android.widget.AdapterView.AdapterContextMenuInfo
import androidx.appcompat.app.AppCompatActivity
import com.example.myapplication.base.BaseActivity
import com.example.myapplication.databinding.NotActivityBinding
import com.example.myapplication.uitls.UiUtils


/**
 * 原蓝牙连接
 */
class BluetoothPrintActivity : BaseActivity<NotActivityBinding>() {
    /**
     * 本设备(手机、电脑等)的蓝牙适配器对象
     */
    private var mBluetoothAdapter: BluetoothAdapter? = null

    //main layout
    private var mMainLayout: LinearLayout? = null

    /**
     * 配对 标题
     */
    private var mPairedTitle: TextView? = null

    /**
     * 配对 列表
     */
    private var mPairedDevicesListView: ListView? = null

    /**
     * 有效的 标题
     */
    private var mAvailableTitle: TextView? = null

    /**
     * 有效设备的 列表
     */
    private var mAvailableDevicesListView: ListView? = null

    /**
     * 扫描 按钮
     */
    private var mScanButton: Button? = null

    /**
     * 配对的设备集合
     */
    private var mPairedDevList: ArrayAdapter<String>? = null

    /**
     * 有效的设备集合
     */
    private var mAvailableDevList: ArrayAdapter<String>? = null

    /**
     * 选择的设备
     */
    private var mBtDevChosen: String? = null

    /**
     * 设备名
     */
    private var mBtDevName: String? = null

    override fun initLayout() {
    }

    override fun initView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && UiUtils.isTranslucentOrFloating(this)) {
            UiUtils.fixOrientation(this)
        }
        mainlayout_create()
        setResult(RESULT_CANCELED)
        init()
    }

    override fun initData() {
    }

    private fun mainlayout_create() {
        //LinearLayout
        mMainLayout = LinearLayout(this)
        mMainLayout!!.orientation = LinearLayout.VERTICAL
        var myLayoutParam = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.FILL_PARENT,
            LinearLayout.LayoutParams.FILL_PARENT
        )
        mMainLayout!!.layoutParams = myLayoutParam
        //TextView
        mPairedTitle = TextView(this)
        myLayoutParam = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.FILL_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        mPairedTitle!!.layoutParams = myLayoutParam
        mPairedTitle!!.text = "已绑定设备"
        mPairedTitle!!.visibility = View.GONE
        mPairedTitle!!.setBackgroundColor(-0x99999a)
        mPairedTitle!!.setTextColor(-0x1)
        mPairedTitle!!.setPadding(5, 0, 0, 0)
        //ListView
        mPairedDevicesListView = ListView(this)
        myLayoutParam = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.FILL_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT,
            2f
        )
        mPairedDevicesListView!!.layoutParams = myLayoutParam
        mPairedDevicesListView!!.isStackFromBottom = true

        //TextView
        mAvailableTitle = TextView(this)
        myLayoutParam = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.FILL_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        mAvailableTitle!!.layoutParams = myLayoutParam
        mAvailableTitle!!.text = "有效设备"
        mAvailableTitle!!.visibility = View.GONE
        mAvailableTitle!!.setBackgroundColor(-0x99999a)
        mAvailableTitle!!.setTextColor(-0x1)
        mAvailableTitle!!.setPadding(5, 0, 0, 0)
        //ListView
        mAvailableDevicesListView = ListView(this)
        myLayoutParam = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.FILL_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT,
            2f
        )
        mAvailableDevicesListView!!.layoutParams = myLayoutParam
        mAvailableDevicesListView!!.isStackFromBottom = true

        //Button
        mScanButton = Button(this)
        myLayoutParam = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.FILL_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        mScanButton!!.layoutParams = myLayoutParam
        mScanButton!!.text = "扫描"
        setTitle("选择打印机")
        mMainLayout!!.addView(mPairedTitle)
        mMainLayout!!.addView(mPairedDevicesListView)
        mMainLayout!!.addView(mAvailableTitle)
        mMainLayout!!.addView(mAvailableDevicesListView)
        mMainLayout!!.addView(mScanButton)
        setContentView(mMainLayout)
    }

    private fun init() {
        //得到蓝牙适配器
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        if (mBluetoothAdapter == null) {
            toast("蓝牙适配器没获得!")
            finish()
        }
        //得到显示 设备名字 地址  设置点击事件（用菜单设置）
        mPairedDevList = ArrayAdapter(this, android.R.layout.simple_list_item_1)
        mPairedDevicesListView!!.adapter = mPairedDevList
        mPairedDevicesListView!!.onItemClickListener = mBtDeviceClicked
        registerForContextMenu(mPairedDevicesListView)
        bonded_devices_get()
        //得到显示其他有效的 名字和地址，设置点击事件
        mAvailableDevList = ArrayAdapter(this, android.R.layout.simple_list_item_1)
        mAvailableDevicesListView!!.adapter = mAvailableDevList
        mAvailableDevicesListView!!.onItemClickListener = mBtDeviceClicked
        registerForContextMenu(mAvailableDevicesListView)
        mScanButton!!.setOnClickListener { v -> //TODO Auto-generated method stub
            v.visibility = View.GONE
            find_do()
        }
        //广播
        val intent = IntentFilter()
        intent.addAction(BluetoothDevice.ACTION_FOUND) // 用BroadcastReceiver来取得搜索结果
        intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
        intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
        registerReceiver(mBroadcastReceiver, intent)
//        var bluetooth = Bluetooth.getBluetooth(this)
//        bluetooth.doDiscovery()
    }


    private val mBtDeviceClicked =
        AdapterView.OnItemClickListener { arg0, v, arg2, arg3 -> // TODO Auto-generated method stub
            if (mBluetoothAdapter!!.isDiscovering) {
                mBluetoothAdapter!!.cancelDiscovery()
            }
            val BtDeviceInfo = (v as TextView).text.toString()
            if (BtDeviceInfo.split("\n".toRegex()).toTypedArray().size <= 1) {
                toast("请选择有效的设备!")
                return@OnItemClickListener
            } else {
                mBtDevName = BtDeviceInfo.split("\n".toRegex()).toTypedArray()[0]
                mBtDevChosen = BtDeviceInfo.substring(BtDeviceInfo.length - 17)
                activity_result_set(mBtDevChosen)
            }
        }

    /**
     * 配对并连接
     *
     * @param BtDeviceAddress
     */
    private fun activity_result_set(BtDeviceAddress: String?) {
//		Log.e("蓝牙设备名称", mBtDevName)
        Log.e("sss2", mBtDevName.toString())
        Log.e("sss3", BtDeviceAddress.toString())
        val intent = Intent()
        intent.putExtra(EXTRA_BLUETOOTH_DEVICE_NAME, mBtDevName)
        intent.putExtra(EXTRA_BLUETOOTH_DEVICE_ADDRESS, BtDeviceAddress)
        intent.putExtra(EXTRA_DEVICE_ADDRESS, BtDeviceAddress)
        intent.action = "设备信息"
        sendBroadcast(intent)
        setResult(RESULT_OK, intent)
        finish()
    }

    /**
     * 绑定设备 list
     */

    private fun bonded_devices_get() {
        mPairedDevList!!.clear()
        Handler().postDelayed({
            val PairedDevices = mBluetoothAdapter!!.bondedDevices
            if (PairedDevices.size > 0) {
                mPairedTitle!!.visibility = View.VISIBLE
                for (device in PairedDevices) {
                    val device_info = """
                        ${device.name}
                        ${device.address}
                        """.trimIndent()
                    mPairedDevList!!.add(device_info)
                }
            } else {
                mPairedTitle!!.visibility = View.GONE
                mPairedDevList!!.add("没有可用的设备")
            }
        }, 3000)
    }

    /**
     * 查询蓝牙设备
     */

    private fun find_do() {
        if (!mBluetoothAdapter!!.isEnabled) {
            //打开蓝牙
            //异步的，不会等待结果，直接返回
            mBluetoothAdapter!!.enable()
            //蓝牙已经打开
            while (mBluetoothAdapter!!.state != BluetoothAdapter.STATE_ON);
        }
        //activity的标题栏显示进度条
        setProgressBarIndeterminateVisibility(true)
        setTitle("扫描设备...")
        //  功能： 是否正在处于扫描过程中。
        //  注意： 如果蓝牙没有开启，该方法会返回false。
        if (mBluetoothAdapter!!.isDiscovering) {
            // 功能： 取消扫描过程。
            // 注意： 如果蓝牙没有开启，该方法会返回false。
            mBluetoothAdapter!!.cancelDiscovery()
        }
        //  功能： 扫描蓝牙设备
        //  注意： 如果蓝牙没有开启，该方法会返回false ，即不会开始扫描过程。
        mBluetoothAdapter!!.startDiscovery()
    }

    var mBroadcastReceiver: BroadcastReceiver? = object : BroadcastReceiver() {

        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            Log.e("sss", action.toString())
            //扫描到了任一蓝牙设备
            //蓝牙扫描时，扫描到任一远程蓝牙设备时，会发送此广播。
            if (BluetoothDevice.ACTION_FOUND == action) {
                val device =
                    intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                if (device!!.bondState != BluetoothDevice.BOND_BONDED) {
                    //可用设备
                    mAvailableTitle!!.visibility = View.VISIBLE
                    mAvailableDevList!!.add(
                        """
    ${device.name}
    ${device.address}
    """.trimIndent()
                    )
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED == action) {
                setProgressBarIndeterminateVisibility(false)
                setTitle("选择设备")
                if (mAvailableDevList!!.count == 0) {
                    mAvailableDevList!!.add("没有可用设备!")
                }
            }
        }
    }

    /**
     * 取消配对
     *
     * @param BtAddress
     */

    private fun paired_cancel(BtAddress: String?) {
        try {
            val device = mBluetoothAdapter!!.getRemoteDevice(BtAddress)
            val CancelPairedMethod = device.javaClass.getMethod(
                "removeBond"
            )
            CancelPairedMethod.invoke(device)
            while (device.bondState == BluetoothDevice.BOND_BONDED);
            bonded_devices_get()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onCreateContextMenu(menu: ContextMenu, v: View, menuInfo: ContextMenuInfo) {
        // TODO Auto-generated method stub
        if (!mBluetoothAdapter!!.isEnabled) {
            //异步的，不会等待结果，直接返回
            mBluetoothAdapter!!.enable()
            while (mBluetoothAdapter!!.state != BluetoothAdapter.STATE_ON);
        }
        super.onCreateContextMenu(menu, v, menuInfo)
        val device_info = (v as ListView).getItemAtPosition(
            (menuInfo as AdapterContextMenuInfo).position
        ).toString()
        mBtDevName = device_info.split("\n".toRegex()).toTypedArray()[0]
        mBtDevChosen = device_info.substring(device_info.length - 17)
        menu.setHeaderTitle(mBtDevName)
        val device = mBluetoothAdapter!!.getRemoteDevice(mBtDevChosen)
        menu.clear()
        if (device.bondState == BluetoothDevice.BOND_BONDED) {
            menu.add("取消配对")
        } else {
            menu.add("配对并连接")
        }
    }

    override fun onContextItemSelected(item: MenuItem): Boolean {
        if (item.toString() === "取消配对") {
            paired_cancel(mBtDevChosen)
        } else if (item.toString() === "配对并连接") {
            activity_result_set(mBtDevChosen)
        }
        return super.onContextItemSelected(item)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mBroadcastReceiver != null) {
            unregisterReceiver(mBroadcastReceiver)
        }
    }

    companion object {
        const val EXTRA_BLUETOOTH_DEVICE_ADDRESS = "Bluetooth Device Adrress"
        const val EXTRA_BLUETOOTH_DEVICE_NAME = "Bluetooth Device Name"
        const val EXTRA_DEVICE_ADDRESS = "address"
    }


}